package com.yxy.gui;

import com.yxy.dao.DbManager;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class MainFrame {
    private JFrame mainFrame;
    private JDesktopPane desktopPane;
    private String userType; // 保存用户类型

    public MainFrame(String userType) {
        this.userType = userType;

        // 创建主界面窗口
        mainFrame = new JFrame("学生选课系统主界面");
        mainFrame.setSize(800, 600);
        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mainFrame.setLocationRelativeTo(null);
        desktopPane = new JDesktopPane();
        mainFrame.add(desktopPane, BorderLayout.CENTER);

        // 创建菜单栏
        JMenuBar menuBar = new JMenuBar();
        JMenu systemMenu = new JMenu("系统管理");
        menuBar.add(systemMenu);

        // 添加原有菜单项
        menuBar.add(new JMenu("学生管理"));
        menuBar.add(new JMenu("班级管理"));
        menuBar.add(new JMenu("教师管理"));
        menuBar.add(new JMenu("课程管理"));
        menuBar.add(new JMenu("选课管理"));
        menuBar.add(new JMenu("帮助"));

        // 如果是管理员登录，添加“学生管理”菜单项
        if ("管理员".equals(userType)) {
            JMenu studentMenu = menuBar.getMenu(1); // 确保取到正确的菜单

            // 添加学生信息功能
            JMenuItem addStudentItem = new JMenuItem("添加学生信息");
            studentMenu.add(addStudentItem);
            addStudentItem.addActionListener(e -> showAddStudentInternalFrame());

            // 查询学生信息功能
            JMenuItem queryStudentItem = new JMenuItem("查询学生信息");
            studentMenu.add(queryStudentItem);
            queryStudentItem.addActionListener(e -> showQueryStudentInternalFrame());
        }

        // 添加菜单栏到框架
        mainFrame.setJMenuBar(menuBar);

        // 显示主界面窗口
        mainFrame.setVisible(true);
    }

    private void showAddStudentInternalFrame() {
        JInternalFrame internalFrame = new JInternalFrame("添加学生信息", true, true, true, true);
        internalFrame.setSize(400, 300);
        internalFrame.setLocation((desktopPane.getWidth() - internalFrame.getWidth()) / 2,
                (desktopPane.getHeight() - internalFrame.getHeight()) / 2); // 中心化
        internalFrame.setVisible(true);
        internalFrame.setLayout(new GridBagLayout());

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;

        // 学生姓名
        JLabel nameLabel = new JLabel("学生姓名：");
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.anchor = GridBagConstraints.WEST; // 左对齐
        internalFrame.add(nameLabel, gbc);

        JTextField nameField = new JTextField(20);
        gbc.gridx = 1;
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        internalFrame.add(nameField, gbc);

        // 所属班级
        JLabel classLabel = new JLabel("所属班级：");
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.gridwidth = 1;
        gbc.anchor = GridBagConstraints.WEST; // 左对齐
        internalFrame.add(classLabel, gbc);

        JComboBox<String> classComboBox = new JComboBox<>(loadClassNames());
        gbc.gridx = 1;
        gbc.gridwidth = GridBagConstraints.REMAINDER; // 与其他组件等宽
        internalFrame.add(classComboBox, gbc);
        classComboBox.setPrototypeDisplayValue("XXXXXXXXXX"); // 设置宽度与其他输入框一致

        // 登录密码
        JLabel passwordLabel = new JLabel("登录密码：");
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.gridwidth = 1;
        gbc.anchor = GridBagConstraints.WEST; // 左对齐
        internalFrame.add(passwordLabel, gbc);

        JPasswordField passwordField = new JPasswordField(20);
        gbc.gridx = 1;
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        internalFrame.add(passwordField, gbc);

        // 学生性别
        JLabel genderLabel = new JLabel("学生性别：");
        gbc.gridx = 0;
        gbc.gridy = 3;
        gbc.gridwidth = 1;
        gbc.anchor = GridBagConstraints.WEST; // 左对齐
        internalFrame.add(genderLabel, gbc);

        JRadioButton maleButton = new JRadioButton("男");
        JRadioButton femaleButton = new JRadioButton("女");
        ButtonGroup genderGroup = new ButtonGroup();
        genderGroup.add(maleButton);
        genderGroup.add(femaleButton);
        JPanel genderPanel = new JPanel(new FlowLayout());
        genderPanel.add(maleButton);
        genderPanel.add(femaleButton);
        gbc.gridx = 1;
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        internalFrame.add(genderPanel, gbc);

        // 确认按钮
        JButton confirmButton = new JButton("确认");
        gbc.gridx = 0;
        gbc.gridy = 4;
        gbc.gridwidth = 1;
        gbc.anchor = GridBagConstraints.WEST; // 左对齐
        internalFrame.add(confirmButton, gbc);

        // 重置按钮
        JButton resetButton = new JButton("重置");
        gbc.gridx = 2; // 将按钮放到右边位置，以列索引2为基础
        gbc.anchor = GridBagConstraints.EAST; // 右对齐
        internalFrame.add(resetButton, gbc);

        // 添加确认按钮功能
        confirmButton.addActionListener(actionEvent -> {
            try {
                String name = nameField.getText();
                String className = (String) classComboBox.getSelectedItem();
                String password = new String(passwordField.getPassword());
                String gender = maleButton.isSelected() ? "男" : "女";
                addStudentToDatabase(name, className, password, gender);
                JOptionPane.showMessageDialog(internalFrame, "学生信息添加成功！");
            } catch (Exception e) {
                JOptionPane.showMessageDialog(internalFrame, "添加失败: " + e.getMessage());
            }
        });

        // 添加重置按钮功能
        resetButton.addActionListener(e -> {
            nameField.setText("");
            passwordField.setText("");
            classComboBox.setSelectedIndex(0);
            genderGroup.clearSelection();
        });

        desktopPane.add(internalFrame);
        internalFrame.toFront();
    }

    private void showQueryStudentInternalFrame() {
        JInternalFrame internalFrame = new JInternalFrame("查询学生信息", true, true, true, true);
        internalFrame.setSize(600, 500);
        internalFrame.setLocation((desktopPane.getWidth() - internalFrame.getWidth()) / 2,
                (desktopPane.getHeight() - internalFrame.getHeight()) / 2);
        internalFrame.setVisible(true);
        internalFrame.setLayout(new BorderLayout());

        // 搜索面板
        JPanel searchPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;

        JLabel nameLabel = new JLabel("学生姓名：");
        gbc.gridx = 0;
        gbc.gridy = 0;
        searchPanel.add(nameLabel, gbc);

        JTextField nameField = new JTextField(10);
        gbc.gridx = 1;
        searchPanel.add(nameField, gbc);

        JLabel classLabel = new JLabel("所属班级：");
        gbc.gridx = 2;
        searchPanel.add(classLabel, gbc);

        JComboBox<String> classComboBox = new JComboBox<>(loadClassNames());
        gbc.gridx = 3;
        classComboBox.setPrototypeDisplayValue("XXXXXXXXXX");
        searchPanel.add(classComboBox, gbc);

        JButton searchButton = new JButton("查询");
        gbc.gridx = 4;
        searchPanel.add(searchButton, gbc);

        internalFrame.add(searchPanel, BorderLayout.NORTH);

        // 表格面板
        JTable table = new JTable(new DefaultTableModel(new Object[]{"学号", "姓名", "班级", "性别", "密码"}, 0));
        JScrollPane scrollPane = new JScrollPane(table);
        internalFrame.add(scrollPane, BorderLayout.CENTER);

        // 操作面板
        JPanel operationPanel = new JPanel(new GridLayout(2, 1, 5, 5));

        // 第一行：修改
        JPanel modifyPanel = new JPanel(new GridBagLayout());
        gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;

        JTextField modifyNameField = new JTextField(10);
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 1;
        modifyPanel.add(new JLabel("学生姓名："), gbc);
        gbc.gridx = 1;
        modifyPanel.add(modifyNameField, gbc);

        JPanel genderPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
        JRadioButton modMaleButton = new JRadioButton("男");
        JRadioButton modFemaleButton = new JRadioButton("女");
        ButtonGroup modGenderGroup = new ButtonGroup();
        modGenderGroup.add(modMaleButton);
        modGenderGroup.add(modFemaleButton);
        genderPanel.add(new JLabel("性别："));
        genderPanel.add(modMaleButton);
        genderPanel.add(modFemaleButton);
        gbc.gridx = 2;
        modifyPanel.add(genderPanel, gbc);

        JButton modifyButton = new JButton("确认修改");
        gbc.gridx = 3;
        modifyPanel.add(modifyButton, gbc);

        operationPanel.add(modifyPanel);

        // 第二行：删除
        JPanel deletePanel = new JPanel(new GridBagLayout());
        gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;

        JComboBox<String> deleteClassComboBox = new JComboBox<>(loadClassNames());
        gbc.gridx = 0;
        gbc.gridy = 0;
        deletePanel.add(new JLabel("所属班级："), gbc);
        gbc.gridx = 1;
        deletePanel.add(deleteClassComboBox, gbc);

        JTextField passwordField = new JTextField(10);
        gbc.gridx = 2;
        deletePanel.add(new JLabel("密码："), gbc);
        gbc.gridx = 3;
        deletePanel.add(passwordField, gbc);

        JButton deleteButton = new JButton("确认删除");
        gbc.gridx = 4;
        deletePanel.add(deleteButton, gbc);

        operationPanel.add(deletePanel);

        internalFrame.add(operationPanel, BorderLayout.SOUTH);

        // 查询按钮动作
        searchButton.addActionListener(e -> {
            String name = nameField.getText();
            String className = (String) classComboBox.getSelectedItem();
            loadStudentData(table, name, className);
        });

        modifyButton.addActionListener(e -> {
            // 验证是否选中了行
            if (table.getSelectedRow() != -1 && !modifyNameField.getText().trim().isEmpty()) {
                try {
                    int selectedRow = table.getSelectedRow();
                    String id = table.getValueAt(selectedRow, 0).toString(); // 从表中获取学生 ID
                    String newName = modifyNameField.getText().trim();
                    String gender = modMaleButton.isSelected() ? "男" : "女";
                    String newPassword = passwordField.getText();

                    // 确保字段不是空的
                    if (newPassword.trim().isEmpty()) {
                        JOptionPane.showMessageDialog(mainFrame, "密码不能为空");
                        return;
                    }

                    updateStudentData(id, newName, gender, newPassword);
                    loadStudentData(table, "", ""); // 刷新表数据

                    JOptionPane.showMessageDialog(mainFrame, "学生信息修改成功");
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(mainFrame, "修改操作失败: " + ex.getMessage());
                }
            } else {
                JOptionPane.showMessageDialog(mainFrame, "请选择一行并输入所有必要的信息");
            }
        });

        deleteButton.addActionListener(e -> {
            // 验证是否选中了行
            if (table.getSelectedRow() != -1 && !passwordField.getText().trim().isEmpty()) {
                try {
                    int selectedRow = table.getSelectedRow();
                    String id = table.getValueAt(selectedRow, 0).toString(); // 从表中获取学生 ID
                    String className = (String) deleteClassComboBox.getSelectedItem();
                    String password = passwordField.getText();

                    deleteStudentData(id, className, password);

                    JOptionPane.showMessageDialog(mainFrame, "学生信息删除成功");
                    loadStudentData(table, "", ""); // 刷新表数据
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(mainFrame, "删除操作失败: " + ex.getMessage());
                }
            } else {
                JOptionPane.showMessageDialog(mainFrame, "请选择一行并输入必要的密码");
            }
        });

        desktopPane.add(internalFrame);
        internalFrame.toFront();
    }

    private void loadStudentData(JTable table, String name, String className) {
        String query = "SELECT s.id, s.name, c.name AS class, s.sex, s.password " +
                "FROM student s LEFT JOIN sclass c ON s.classid = c.id " +
                "WHERE s.name LIKE ? AND c.name LIKE ?";

        try (Connection conn = DbManager.getConnection();
             PreparedStatement stmt = conn.prepareStatement(query)) {

            stmt.setString(1, "%" + name + "%");
            stmt.setString(2, "%" + className + "%");
            ResultSet rs = stmt.executeQuery();

            DefaultTableModel model = (DefaultTableModel) table.getModel();
            model.setRowCount(0); // 清空表格

            while (rs.next()) {
                model.addRow(new Object[]{
                        rs.getInt("id"),
                        rs.getString("name"),
                        rs.getString("class"),
                        rs.getString("sex"),
                        rs.getString("password")
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(mainFrame, "查询失败: " + e.getMessage());
        }
    }

    private void updateStudentData(String id, String name, String gender, String password) {
        String query = "UPDATE student SET name = ?, sex = ?, password = ? WHERE id = ?";
        try (Connection conn = DbManager.getConnection();
             PreparedStatement stmt = conn.prepareStatement(query)) {
            stmt.setString(1, name);
            stmt.setString(2, gender);
            stmt.setString(3, password);
            stmt.setString(4, id);
            stmt.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void deleteStudentData(String id, String className, String password) {
        String query = "DELETE FROM student WHERE id = ? AND password = ? AND classid = " +
                "(SELECT id FROM sclass WHERE name = ?)";
        try (Connection conn = DbManager.getConnection();
             PreparedStatement stmt = conn.prepareStatement(query)) {
            stmt.setString(1, id);
            stmt.setString(2, password);
            stmt.setString(3, className);
            stmt.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String[] loadClassNames() {
        List<String> classNames = new ArrayList<>();
        String query = "SELECT name FROM sclass";
        try (Connection conn = DbManager.getConnection();
             PreparedStatement stmt = conn.prepareStatement(query);
             ResultSet rs = stmt.executeQuery()) {
            while (rs.next()) {
                classNames.add(rs.getString("name"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(mainFrame, "无法加载班级信息: " + e.getMessage());
        }
        return classNames.toArray(new String[0]);
    }

    private void addStudentToDatabase(String name, String className, String password, String gender) throws Exception {
        String query = "INSERT INTO student (name, classid, password, sex) VALUES (?, (SELECT id FROM sclass WHERE name = ?), ?, ?)";
        try (Connection conn = DbManager.getConnection();
             PreparedStatement stmt = conn.prepareStatement(query)) {
            stmt.setString(1, name);
            stmt.setString(2, className);
            stmt.setString(3, password);
            stmt.setString(4, gender);
            stmt.executeUpdate();
        }
    }
}